package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.CollectedStoreEntity;
import com.zw.yzk.kabu.data.network.service.CollectedStoreService;
import com.zw.yzk.kabu.data.network.task.CollectedStoreTask;
import com.zw.yzk.kabu.data.network.task.Task;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class CollectedStoreRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public CollectedStoreRepository() {
        totalCount = CollectedStoreTask.DEFAULT_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        CollectedStoreService service = ServiceGenerator.createService(CollectedStoreService.class);
        CollectedStoreTask storeTask = (CollectedStoreTask) addToken(task);

        if (storeTask.start >= totalCount) {
            CollectedStoreEntity entity = new CollectedStoreEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            return service.getCollectedStore(
                    storeTask.start,
                    storeTask.size,
                    storeTask.userId,
                    storeTask.accessToken);
        }
    }

    @Override
    protected Func1<CollectedStoreEntity, Observable> getServerData() {
        return new Func1<CollectedStoreEntity, Observable>() {
            @Override
            public Observable call(CollectedStoreEntity entity) {
                totalCount = entity.result.total;
                return Observable.just(entity);
            }
        };
    }

}
